﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using OrderWebApplication.Models;
using System;
using System.Collections.Generic;
using System.Linq;

namespace OrderWebApplication.Controllers {
    [Route("Order")]
    [ApiController]
    public class OrderController : ControllerBase {

        private readonly OrderModel context;

        public OrderController(OrderModel _context) {
            context = _context;
        }

        [HttpGet]
        public List<Order> Get() {
            if (!context.Orders.Any()) {
                Order order = new Order();
                Customer customer = new Customer();
                OrderDetail orderDetail = new OrderDetail();
                Commodity commodity = new Commodity();
                OrderDetail orderDetail1 = new OrderDetail();
                customer.Name = "Nadad2";
                commodity.Name = "da3f";
                commodity.UnitPrice = 12;
                orderDetail.Commodity = commodity;
                orderDetail.Amount = 5;
                order.Customer = customer;
                order.Details = new List<OrderDetail>();
                order.Details.Add(orderDetail);
                order.ShippingAddress = "dak4";
                context.Add(order);
                context.SaveChanges();
            }
            var query = context.Orders.Include("Customer").Include("Details").Include("Details.Commodity");
            return query.ToList();
        }

        [HttpPost("addOrder")]
        public String AddPost(Order addOrder) {
            context.Add(addOrder);
            int result = context.SaveChanges();

            return new JObject {
                { "status", "OK" }
            }.ToString();
        }

        [HttpPost("deleteOrder")]
        public String DeletePost() {
            int orderId = Convert.ToInt32(Request.Form["orderId"]);
            var deleteOrder = context.Orders.Include("Customer").Include("Details").Include("Details.Commodity").FirstOrDefault(p => p.OrderId == orderId);
            if (deleteOrder != null) {
                context.Orders.Remove(deleteOrder);
                int result = context.SaveChanges();
                return new JObject {
                    { "status", "OK" }
                }.ToString();
            }

            return new JObject {
                { "status", "ERROR" },
                { "Reason", "No Such Order Which OrderId = " +orderId}
            }.ToString();
        }
    }
}
